package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import jdk.nashorn.internal.ir.CallNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品 同时保存对应口味数据
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表
        this.save(dishDto);

        Long dishId = dishDto.getId(); //菜品id

        List<DishFlavor> flavorList = dishDto.getFlavors();
        flavorList.forEach(s -> s.setDishId(dishId));

        //保存菜品口味数据到菜品口味表 dish_flavor
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    public void updatewithFalvor(DishDto dishDto) {

        //falvor可能是从无增加的 不存在id 所以不能用更新 要清空保存
        //list.forEach(s -> dishFlavorService.updateById(s));

        updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);


        Long dishId = dishDto.getId(); //菜品id
        List<DishFlavor> flavorList = dishDto.getFlavors();
        flavorList.forEach(s -> s.setDishId(dishId));

        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    public void removeWithFalvor(Long id) {
        removeById(id);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,id);
        dishFlavorService.removeById(queryWrapper);
    }

    @Override
    public DishDto updateALLById(Long id) {
        Dish dish = getById(id);
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish,dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(list);

        return dishDto;

    }


}
